package io.emqx.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttSample2 {
    public static void main(String[] args) {
        String topic = "1_";
        String content = "Hello World";
        int qos = 2;
        String port = "1883";
        String broker = "tcp://localhost:"+port;
        String clientId = MqttClient.generateClientId();
        String clientId2 = MqttClient.generateClientId();
        System.out.println(clientId);
        System.out.println(clientId2);
        //  持久化
        MemoryPersistence persistence = new MemoryPersistence();
        // MQTT 连接选项
        MqttConnectOptions connOpts = new MqttConnectOptions();
        // 设置认证信息
        connOpts.setUserName("emqx_user1232");
        connOpts.setPassword("emqx_password1232".toCharArray());

        try {
            MqttClient client = new MqttClient(broker, clientId, persistence);
            MqttClient client2 = new MqttClient(broker, clientId+2, persistence);
            // 设置回调
            client.setCallback(new SampleCallback());
            client2.setCallback(new SampleCallback());
            // 建立连接
            System.out.println("Connecting to broker: " + broker);
            client.connect(connOpts);
            client2.connect(connOpts);
            System.out.println("Connected to broker: " + broker);
            // 订阅 topic
            client.subscribe(topic, qos);
            client2.subscribe(topic, qos);
            System.out.println("Subscribed to topic: " + topic);
            // 发布消息

//            client.close();
//            System.exit(0);
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
}

